//
//  RegisterViewController.m
//  GC_OC
//
//  Created by Tianbao Wang on 2022/5/27.
//

#import "RegisterViewController.h"
#import "LoginTextfieldView.h"
#import "UILabel+Attri.h"
#import "UserLoginViewController.h"
#import "Cache.h"
#import "MineViewController.h"
#import "LoginViewController.h"

@interface RegisterViewController ()<UITextFieldDelegate>
@property(nonatomic, strong) UIView *navigationBarView;
@property(nonatomic, strong) LoginTextfieldView *accountView;
@property(nonatomic, strong) LoginTextfieldView *pwdView;
@property(nonatomic, strong) LoginTextfieldView *wtView;
@property(nonatomic, strong) LoginTextfieldView *hdView;

@property(nonatomic, strong) LoginTextfieldView *yzView;
@property(nonatomic, strong) LoginTextfieldView *yzdaView;

@property (nonatomic, strong) ObjectAFNetWorking* objectAFNet;
@property (nonatomic, strong) NSDictionary* verificationDic;
@property (nonatomic, strong) UILabel* doneLabel;
@property (nonatomic, strong) NSString* regCount;
@property (nonatomic, strong) UIButton* doneButton;
@property (nonatomic) BOOL noaccount;

@end

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.objectAFNet = [ObjectAFNetWorking new];
    [self setupUIView];
    [self refreshYz];
}

//- (void)viewWillAppear:(BOOL)animated {
//    [super viewWillAppear:animated];
//    [self.navigationController setNavigationBarHidden:true animated:true];
//    
//}
//
//- (void)viewWillDisappear:(BOOL)animated {
//    [super viewWillDisappear:animated];
//    [self.navigationController setNavigationBarHidden:false animated:true];
//    
//}

- (void)back {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)doneAct {
    [self keyboradDown];
    NSString *key = [NSString stringWithFormat:@"%@_registerCount",[NSString getYYMMDD:[NSDate date]]];
    self.regCount = [[NSUserDefaults standardUserDefaults] objectForKey:key];
    if (self.regCount != nil && [self.regCount intValue] <= 0) {
        [self.view makeToast:@"对不起，今天次数上限，明天再试"];
        return;
    }
    
    if ([self.accountView.textfield.text length] < 5 || self.accountView.textfield.text.length > 20) {
        [self.view makeToast:@"请输入合法的账号"];
        return;
    }
    if (!self.noaccount) {
        [self.view makeToast:@"该账号已注册"];
        return;
    }
    if ([self.pwdView.textfield.text length] < 6 || self.pwdView.textfield.text.length > 30) {
        [self.view makeToast:@"请输入合法的密码"];
        return;
    }
    if ([self.wtView.textfield.text length] >= 20 || [self.wtView.textfield.text length] == 0) {
        [self.view makeToast:@"请输入合法的自定义提问"];
        return;
    }
    if ([self.hdView.textfield.text length] >= 20 || [self.hdView.textfield.text length] == 0) {
        [self.view makeToast:@"请输入合法的自定义回答"];
        return;
    }
    if ([self.yzdaView.textfield.text length] == 0) {
        [self.view makeToast:@"请输入答案"];
        return;
    }
//    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"username"] = self.accountView.textfield.text;
    param[@"password"] = self.pwdView.textfield.text;
    param[@"code"] = self.verificationDic[@"code"];
    param[@"verification_answer"] = self.yzdaView.textfield.text;
    param[@"hint_title"] = self.wtView.textfield.text;
    param[@"hint_answer"] = self.hdView.textfield.text;
    [SVProgressHUD show];
    [FKHttpTool postWithSuffix:@"/api/user/register" param:param success:^(FKBaseResult *result) {
        [SVProgressHUD dismiss];
        if (result.isSuccess) {
            [SVProgressHUD showSuccessWithStatus:result.msg];
            UserModel *user = [UserModel mj_objectWithKeyValues:result.data];
            [Cache shared].userInfo = user;
            [FKCacheTool saveUserInfo:result.data];
            [FKCacheTool saveToken:user.userinfo.token];
            [self.navigationController dismissViewControllerAnimated:true completion:nil];
//            NSMutableArray *vcs = [[NSMutableArray alloc] init];
//            for (int i=0; i<self.navigationController.viewControllers.count; i++) {
//                UIViewController *control = self.navigationController.viewControllers[i];
//                [vcs addObject:control];
//                if ([control isKindOfClass:[LoginViewController class]]) {
//                    [vcs removeObject:control];
//                    break;
//                }
//            }
//            MineViewController *mine = [MineViewController new];
//            mine.hidesBottomBarWhenPushed = YES;
//            [vcs addObject:mine];
//            [self.navigationController setViewControllers:vcs animated:YES];
        } else {
            if ([result.code isEqualToString:@"403"]) {
                [self countReg];
            }
        }
    } failure:^(NSError *error) {
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [self.view makeToast:error.debugDescription];
        [self countReg];
    }];
    
//    [self.objectAFNet postUrlStr:[NSString stringWithFormat:@"%@/api/user/register",server_addr] parames:dic finish:^(id  _Nonnull dataString) {
//        [MBProgressHUD hideHUDForView:self.view animated:YES];
//        NSDictionary* dic=[NSJSONSerialization JSONObjectWithData:dataString options:NSJSONReadingMutableContainers error:nil];
//        if ([dic[@"code"] isEqual:@200]) {
//            NSError *err;
//            UserModel *user = [[UserModel alloc] initWithDictionary:dic[@"data"] error:&err];
//            [Cache shared].userInfo = user;
//            [FKCacheTool saveToken:user.userinfo.token];
//            NSMutableArray *vcs = [[NSMutableArray alloc] init];
//            for (int i=0; i<self.navigationController.viewControllers.count; i++) {
//                UIViewController *control = self.navigationController.viewControllers[i];
//                [vcs addObject:control];
//                if ([control isKindOfClass:[LoginViewController class]]) {
//                    [vcs removeObject:control];
//                    break;
//                }
//            }
//            MineViewController *mine = [MineViewController new];
//            mine.hidesBottomBarWhenPushed = YES;
//            [vcs addObject:mine];
//            [self.navigationController setViewControllers:vcs animated:YES];
//        } else {
//            [self.view makeToast:dic[@"msg"]];
//            if ([dic[@"code"] isEqual:@403]) {
//                [self countReg];
//            }
//        }
//    } andError:^(NSError * _Nonnull error) {
//        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//        [self.view makeToast:error.debugDescription];
//        [self countReg];
//    }];
}

//错误次数
- (void)countReg {
    NSString *key = [NSString stringWithFormat:@"%@_registerCount",[NSString getYYMMDD:[NSDate date]]];
    self.regCount = [[NSUserDefaults standardUserDefaults] objectForKey:key];
    if (!self.regCount) {
        self.regCount = @"3";
    }
    self.regCount = [NSString stringWithFormat:@"%d",[self.regCount intValue]-1];
    [[NSUserDefaults standardUserDefaults] setObject:self.regCount forKey:key];
    
    [self.doneLabel setAttribute:[NSString stringWithFormat:@"确定注册",self.regCount] diff:[NSString stringWithFormat:@"（今日可提交%@次）",self.regCount] diffColor:[UIColor whiteColor] diffFont:[UIFont systemFontOfSize:12]];
}

//获取随机验证码
- (void)refreshYz {
    [self.objectAFNet getUrlStr:[NSString stringWithFormat:@"%@/api/user/verification",server_addr] finish:^(id  _Nonnull dataString) {
        NSDictionary* dic=[NSJSONSerialization JSONObjectWithData:dataString options:NSJSONReadingMutableContainers error:nil];
        if ([dic[@"code"] isEqual:@1]) {
            NSDictionary *data = dic[@"data"];
            self.verificationDic = data;
            self.yzView.textfield.text = data[@"title"];
        }
    } andError:^(NSError * _Nonnull error) {
        
    }];
}

//校验账号是否已存在
- (void)accountCheak {
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    [dict setValue:self.accountView.textfield.text forKey:@"account"];
    
    [self.objectAFNet postUrlStr:[NSString stringWithFormat:@"%@/api/user/verifyuser",server_addr] parames:dict finish:^(id  _Nonnull dataString) {
        NSDictionary* dic=[NSJSONSerialization JSONObjectWithData:dataString options:NSJSONReadingMutableContainers error:nil];
        if ([dic[@"code"] isEqual:@200]) {
            [self.accountView.resultImg setImage:[UIImage imageNamed:@"login_zhengque"] forState:UIControlStateNormal];
            self.noaccount = YES;
        } else if ([dic[@"code"] isEqual:@400]) {
            [self keyboradDown];
            [self.accountView.resultImg setImage:[UIImage imageNamed:@"login_cuowu"] forState:UIControlStateNormal];
            self.noaccount = NO;
            [self.view makeToast:dic[@"msg"]];
        }
    } andError:^(NSError * _Nonnull error) {
        
    }];
}

- (void)loginAct {
    [self.navigationController pushViewController:[UserLoginViewController new] animated:YES];
}

- (void)setupUIView {
    self.view.backgroundColor = UIColor.whiteColor;
    UIImageView *bgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"login_bg"]];
    [self.view addSubview:bgView];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    self.navigationBarView = [UIView new];
    self.navigationBarView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.navigationBarView];
    [self.navigationBarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(self.view);
        make.height.mas_equalTo(NAVI_BAR_HIGHT);
    }];
    
    UILabel *naviTitle = [UILabel new];
    naviTitle.text = @"新用户注册";
    naviTitle.textAlignment = NSTextAlignmentCenter;
    naviTitle.textColor = [UIColor blackColor];
    naviTitle.font = [UIFont systemFontOfSize:20 weight:UIFontWeightMedium];
    [self.navigationBarView addSubview:naviTitle];
    [naviTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.navigationBarView);
        make.top.mas_equalTo(StatusBarHeight);
        make.height.mas_equalTo(40);
    }];
    
    UIButton *backButton = [UIButton new];
    [backButton setImage:[UIImage imageNamed:@"icon_返回_32_left"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationBarView addSubview:backButton];
    [backButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(32);
        make.left.equalTo(self.view).offset(12);
        make.top.mas_equalTo(StatusBarHeight + 4);
    }];
    
    self.accountView = [[LoginTextfieldView alloc] init];
    self.accountView.nameLabel.text = @"账号";
    self.accountView.textfield.placeholder = @"请输入账号";
    self.accountView.textfield.delegate = self;
    [self.view addSubview:self.accountView];
    [self.accountView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.navigationBarView.mas_bottom).offset(15);
        make.height.mas_equalTo(34);
    }];
    
    self.pwdView = [[LoginTextfieldView alloc] init];
    self.pwdView.nameLabel.text = @"密码";
    self.pwdView.textfield.placeholder = @"请输入密码";
    self.pwdView.textfield.delegate = self;
    self.pwdView.textfield.secureTextEntry = YES;
    self.pwdView.isPwd = YES;
    [self.view addSubview:self.pwdView];
    [self.pwdView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.accountView.mas_bottom).offset(15);
        make.height.mas_equalTo(34);
    }];
    
    self.wtView = [[LoginTextfieldView alloc] init];
    self.wtView.nameLabel.text = @"自定义提问";
    self.wtView.textfield.delegate = self;
    self.wtView.textfield.placeholder = @"请牢记您的问题";
    [self.view addSubview:self.wtView];
    [self.wtView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.pwdView.mas_bottom).offset(15);
        make.height.mas_equalTo(34);
    }];
    
    self.hdView = [[LoginTextfieldView alloc] init];
    self.hdView.nameLabel.text = @"自定义回答";
    self.hdView.textfield.delegate = self;
    self.hdView.textfield.placeholder = @"请牢记您的回答";
    [self.view addSubview:self.hdView];
    [self.hdView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.wtView.mas_bottom).offset(15);
        make.height.mas_equalTo(34);
    }];
    
    self.yzView = [[LoginTextfieldView alloc] init];
    self.yzView.nameLabel.text = @"验证：";
    self.yzView.textfield.delegate = self;
    self.yzView.textfield.layer.borderWidth = 0;
    self.yzView.textfield.userInteractionEnabled = NO;
    [self.view addSubview:self.yzView];
    [self.yzView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.hdView.mas_bottom).offset(40);
        make.height.mas_equalTo(34);
    }];
    [self.yzView.resultImg setImage:[UIImage imageNamed:@"tianchongxing"] forState:UIControlStateNormal];
    [self.yzView.resultImg addTarget:self action:@selector(refreshYz) forControlEvents:UIControlEventTouchUpInside];
    
    self.yzdaView = [[LoginTextfieldView alloc] init];
    self.yzdaView.nameLabel.text = @"输入答案：";
    self.yzdaView.textfield.delegate = self;
    [self.view addSubview:self.yzdaView];
    [self.yzdaView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.yzView.mas_bottom).offset(15);
        make.height.mas_equalTo(34);
    }];
    
    self.doneButton = [UIButton new];
    self.doneButton.clipsToBounds = YES;
    self.doneButton.layer.cornerRadius = 28;
    self.doneButton.backgroundColor = XHUIColorFromRGB(0x0091FF);
    [self.doneButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.doneButton addTarget:self action:@selector(doneAct) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.doneButton];
    [self.doneButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(56);
        make.right.equalTo(self.view).offset(-50);
        make.left.equalTo(self.view).offset(50);
        make.top.equalTo(self.yzdaView.mas_bottom).offset(20);
    }];
    
    self.doneLabel = [[UILabel alloc] init];
    self.doneLabel.textColor = [UIColor whiteColor];
    self.doneLabel.font = [UIFont systemFontOfSize:16];
    [self.doneButton addSubview:self.doneLabel];
    [self.doneLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.doneButton);
    }];
    [self.doneLabel setAttribute:@"确定注册" diff:@"（今日可提交3次）" diffColor:[UIColor whiteColor] diffFont:[UIFont systemFontOfSize:12]];
    NSString *key = [NSString stringWithFormat:@"%@_registerCount",[NSString getYYMMDD:[NSDate date]]];
    self.regCount = [[NSUserDefaults standardUserDefaults] objectForKey:key];
    if ([self.regCount intValue] == 3) {
        self.doneButton.userInteractionEnabled = NO;
        self.doneButton.backgroundColor = [UIColor grayColor];
    }
    
    UIButton *loginButton = [UIButton new];
    loginButton.backgroundColor = [UIColor clearColor];
    loginButton.titleLabel.font = [UIFont fontWithName:@"PingFangSC" size: 16];
    [loginButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [loginButton addTarget:self action:@selector(loginAct) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:loginButton];
    [loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(56);
        make.right.equalTo(self.view).offset(-50);
        make.left.equalTo(self.view).offset(50);
        make.top.equalTo(self.doneButton.mas_bottom).offset(32);
    }];
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    if (textField == self.accountView.textfield) {
        if ([self.accountView.textfield.text length] >= 5 && self.accountView.textfield.text.length <= 20) {
            [self accountCheak];
        } else {
            [self.accountView.resultImg setImage:[UIImage imageNamed:@"login_cuowu"] forState:UIControlStateNormal];
        }
    } else if (textField == self.pwdView.textfield) {
        if ([self.pwdView.textfield.text length] >= 6 && self.pwdView.textfield.text.length <= 30) {
            [self.pwdView.resultImg setImage:[UIImage imageNamed:@"login_zhengque"] forState:UIControlStateNormal];
        } else {
            [self.pwdView.resultImg setImage:[UIImage imageNamed:@"login_cuowu"] forState:UIControlStateNormal];
        }
    } else if (textField == self.wtView.textfield) {
        if ([self.wtView.textfield.text length] <= 20 && [self.wtView.textfield.text length] > 0) {
            [self.wtView.resultImg setImage:[UIImage imageNamed:@"login_zhengque"] forState:UIControlStateNormal];
        } else {
            [self.wtView.resultImg setImage:[UIImage imageNamed:@"login_cuowu"] forState:UIControlStateNormal];
        }
    } else if (textField == self.hdView.textfield) {
        if ([self.hdView.textfield.text length] <= 20 && [self.hdView.textfield.text length] > 0) {
            [self.hdView.resultImg setImage:[UIImage imageNamed:@"login_zhengque"] forState:UIControlStateNormal];
        } else {
            [self.hdView.resultImg setImage:[UIImage imageNamed:@"login_cuowu"] forState:UIControlStateNormal];
        }
    } else if (textField == self.yzdaView.textfield) {
        if ([self.yzdaView.textfield.text length] != 0) {
            [self.yzdaView.resultImg setImage:[UIImage imageNamed:@"login_zhengque"] forState:UIControlStateNormal];
        } else {
            [self.yzdaView.resultImg setImage:[UIImage imageNamed:@"login_cuowu"] forState:UIControlStateNormal];
        }
    }
    return YES;
}

- (void)keyboradDown {
    [self.accountView resignFirstResponder];
    [self.pwdView resignFirstResponder];
    [self.wtView resignFirstResponder];
    [self.hdView resignFirstResponder];
    [self.yzView resignFirstResponder];
    [self.yzdaView resignFirstResponder];
}
@end
